#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2018/11/27 17:35
# @Author  : yangdy
# @Email   : yangdy@egu360.com
# @File    : 中级-两整数之和.py
# @Software: PyCharm

from utils.main import main, opt_list


class Solution:
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """

        def sig(num):
            return 1 if num >= 0 else -1

        def cal1(x, y):
            u = x & y
            v = x ^ y
            while u:
                u <<= 1
                u, v = u & v, u ^ v
            return v

        def cal2(x, y):
            p = 0
            ap = 1
            ans = 0
            while x or y:
                xx = x & 1
                yy = y & 1
                ans |= ap * (
                    1 if (xx and not yy and not p) or (yy and not xx and not p) or (p and not yy and not xx) else 0)
                p = 1 if (xx and yy and p) or (not xx and yy or p) else 0
                x >>= 1
                y >>= 1
                ap <<= 1
            return ans

        sa = sig(a)
        sb = sig(b)
        if sa * sb > 0:
            return sa * cal1(sa * a, sb * b)
        else:
            if sa < 0:
                a, b, sa, sb = b, a, sb, sa
            a = sa * a
            b = sb * b
            if a < b:
                return -1 * cal2(b, a)
            else:
                return cal2(a, b)


def opt(a, b):
    solve = Solution()
    print(a, '+', b)
    print('ans:', solve.getSum(a, b))


def opt1():
    opt(1, 3)


def opt2():
    opt(2, -1)


def opt3():
    opt(-2, -4)


def opt4():
    opt(-14, 16)


def opt5():
    opt(2147483647, -2147483648)


if __name__ == '__main__':
    opt_list.append(opt1)
    opt_list.append(opt2)
    opt_list.append(opt3)
    opt_list.append(opt4)
    opt_list.append(opt5)
    main()
